package com.wn34.goods.realms;

import com.wn34.goods.entity.User;
import com.wn34.goods.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        User user = userService.userLogin(username);
        if (user == null) {
            throw new UnknownAccountException("用户名不存在!");
        }

        ByteSource byteSource = ByteSource.Util.bytes(username);

        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(user, user.getPassword(), byteSource, this.getName());

        SecurityUtils.getSubject().getSession().setAttribute("loginUser", user);

        return info;
    }

    public static void main(String[] args) {

    }
}
